﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HikVisionTool.Helper;
using HikVisionTool.DAL;
using CommomDetec;
using System.Net.Sockets;
using Newtonsoft.Json;
using System.Net;
using  HikVisionTool.Model;
using System.Threading;
using HikVisionTool.TcpServer;
using System.Windows.Threading;
using System.IO;
using System.Collections.ObjectModel;
using MesTool;
using 通用过站与数采.BLL;
using 通用过站与数采.ViewModel;
using LiveCharts.Wpf;
using System.Data.SqlClient;
using System.Data;
using System.Reflection.Emit;
using System.Xml.Linq;

namespace 通用过站与数采
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
         //CommonDetecHelper commonDetecHelper = null;//通用检测协议解析帮助类
         //AsyncTCPServer server = new AsyncTCPServer(9999);
        HikVisonDAL hikVisonDAL = new HikVisionTool.DAL.HikVisonDAL();
        SolidColorBrush WaitColor = new SolidColorBrush(Colors.Gold);
        SolidColorBrush PassColor = new SolidColorBrush(Colors.LightGreen);
        SolidColorBrush OkColor = new SolidColorBrush(Colors.ForestGreen);
         SolidColorBrush NgColor = new SolidColorBrush(Colors.Tomato);
        DispatcherTimer timer1 = new DispatcherTimer();
        DispatcherTimer timer2 = new DispatcherTimer();
        public string line = "";
        public string Jiwei = "";
        public int pline = 0;
        // 供应商编号，固定值
        public string lifnr = "105464";
        // 工序编号，固定值
        public string processid = "";
        // 扫描工位，固定值
        public string wkposition = "";
        public string order = "";

        BLL.HikDataBLL hikDataBLL;
        BLL.MesBLL mesBLL = new BLL.MesBLL();

        object listLock = new object();
        object upLock = new object();
        List<Sql2Helper.t_Item> t_Items = new List<Sql2Helper.t_Item>();
        //List<Sql5Helper.t_org_tree> t_org_trees = new List<Sql5Helper.t_org_tree>();
        ViewModel.MainViewModel viewModel = new ViewModel.MainViewModel();
        private UserDAL userDAL = new UserDAL();
        public Sql2Helper.t_DD_UserDetail userModel = null;
        private bool isQimi = false;
        private bool isZhuangpei = false;
        //THT通用测试
        //THT加密升级
        //高清网络检测
        string operation = "手动高清网络检测";
        private KeyboardHook scanHook = new KeyboardHook();
        public MainWindow()
        {
            HandyControl.Tools.ConfigHelper.Instance.SetLang("zh-cn");
            InitializeComponent();
            this.WindowStartupLocation = WindowStartupLocation.Manual;
            this.Left = 0;
            this.Top = 0;
            this.Title = operation + "过站与数采（日志读取版）";
        }
        //private void THTInit()
        //{
        //    bool flag = this.operation == "THT通用测试";
        //    if (flag)
        //    {
        //        this.ComboBoxWkPosition.Items.Add("THT通用测试");
        //        this.ComboBoxLine.Items.Add("测试3线");
        //    }
        //    bool flag2 = this.operation == "THT加密升级";
        //    if (flag2)
        //    {
        //        this.ComboBoxWkPosition.Items.Add("THT加密升级");
        //        this.ComboBoxLine.Items.Add("测试2线");
        //    }
        //}
        private void InitLines()
        {
            ComboBoxWkPosition.Items.Add(operation);
            if (operation.Contains("高清"))
            {
                TextBlockJiWei.Text = "工  序";
                t_Items = hikVisonDAL.GetIPCLines().OrderBy(it => it.itemName.Length).ThenBy(it => it.itemName).ToList();
                TextBoxJiWei.Visibility = Visibility.Hidden;
                RadioButtonQiMi.Visibility = Visibility.Visible;
                RadioButtonZhuangPei.Visibility = Visibility.Visible;
                foreach (var item in t_Items)
                {
                    ComboBoxLine.Items.Add(item.itemName);
                }
            }
            if (operation.Contains("THT"))
            {
                bool flag = this.operation == "THT通用测试";
                if (flag)
                {
                    this.ComboBoxLine.Items.Add("测试3线");
                }
                bool flag2 = this.operation == "THT加密升级";
                if (flag2)
                {
                    this.ComboBoxLine.Items.Add("测试2线");
                }
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                //bool flag = this.operation.Contains("THT");
                //if (flag)
                //{
                    this.InitLines();
                //}
                Dictionary<string, string> dic = ConfigHelper.ReadAll();
                //TextBoxName.Text = dic["name"];
                ComboBoxLine.SelectedValue = dic["line"];
                ComboBoxWkPosition.SelectedValue = dic["wkposition"];
                TextBoxJiWei.Text = dic["jiwei"];
                //TCPInit(0);
                viewModel.Enable = true;
                viewModel.Items = new ObservableCollection<ViewModel.MainViewModel.Item>();
                timer1.Tick += new EventHandler(timer1_Tick);
                timer1.Interval = new TimeSpan(20000000);
                timer2.Tick += new EventHandler(timer2_Tick);
                timer2.Interval = new TimeSpan(100000000);
                hikDataBLL = new BLL.HikDataBLL(this);
                this.DataContext = viewModel; 
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("SQL"))
                {
                    HandyControl.Controls.MessageBox.Error("数据库连接异常");
                }
                else
                {
                    HandyControl.Controls.MessageBox.Error(ex.Message);
                }
                FileHelper.WriteLog(ex.ToString());
            }
        }
        bool change = false;
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                Dispatcher.Invoke(() =>
                {
                    if (viewModel.Items.Count > 0 && change)
                    {
                        Thread.Sleep(10);
                        SetPie();
                        //List.ScrollIntoView(List.Items[List.Items.Count - 1]);
                        TextBoxOrder.Text = order;
                        change = false;
                    }
                });
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error(ex.Message);
                FileHelper.WriteLog(ex.ToString());
            }
        }
        private void timer2_Tick(object sender, EventArgs e)
        {
            try
            {
                lock (upLock)
                {
                    Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            if (hikVisonDAL.sql3Helper.SqlCheck() == false)
                            {
                                return;
                            }
                            if (wkposition == "THT通用测试")
                            {
                                hikDataBLL.UpOfflineData2();
                            }
                            if (wkposition == "THT加密升级")
                            {
                                hikDataBLL.UpOfflineData();
                            }
                        }
                        catch (Exception ex)
                        {
                            FileHelper.WriteLog(ex.ToString());
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error(ex.Message);
                FileHelper.WriteLog(ex.ToString());
            }
        }
        private void BorderStart_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (PackIconStart.Kind == MaterialDesignThemes.Wpf.PackIconKind.Play)
                {
                    if (ComboBoxLine.Text == "")
                    {
                        HandyControl.Controls.MessageBox.Warning("请先选择线别!");
                        return;
                    }
                    if (ComboBoxWkPosition.Text == "")
                    {
                        HandyControl.Controls.MessageBox.Warning("请先选择工位!");
                        return;
                    }
                    if (operation.Contains("THT"))
                    {
                        if (TextBoxJiWei.Text == "")
                        {
                            HandyControl.Controls.MessageBox.Warning("请先输入机位!");
                            return;
                        }
                        if (int.TryParse(TextBoxJiWei.Text, out int a) == false)
                        {
                            HandyControl.Controls.MessageBox.Warning("机位输入错误!");
                            return;
                        }
                    }
                    if (TextBoxName.Text.Trim() == "")
                    {
                        HandyControl.Controls.MessageBox.Warning("请先输入工号!");
                        return;
                    }
                    userModel = userDAL.GetUser(TextBoxName.Text.Trim());
                    if (userModel == null)
                    {
                        HandyControl.Controls.MessageBox.Error("姓名获取失败");
                        return;
                    }
                   
                    line = ComboBoxLine.Text;
                    TextBoxName.Text = userModel.username;
                    wkposition = ComboBoxWkPosition.Text;
                    bool flag9 = this.wkposition == "THT通用测试" || this.wkposition == "THT加密升级";
                    if (flag9)
                    {
                        this.pline = ((this.wkposition == "THT通用测试") ? 145 : 119);
                        this.processid = "641";
                        this.Jiwei = this.TextBoxJiWei.Text;
                    }
                    if (operation.Contains("高清"))
                    {
                        pline = t_Items[ComboBoxLine.SelectedIndex].id;
                        processid = "050";
                        isQimi = RadioButtonQiMi.IsChecked == true;
                        isZhuangpei = RadioButtonZhuangPei.IsChecked == true;
                    }

                    Jiwei = TextBoxJiWei.Text;
                    viewModel.Enable = false;
                    BorderStart.Background = NgColor;
                    PackIconStart.Kind = MaterialDesignThemes.Wpf.PackIconKind.Stop;
                    PoptipStart.Content = "停止采集";
                    //server.Start();
                    timer1.Start();
                    timer2.Start();
                    scanHook = new KeyboardHook();
                    scanHook.BarCodeEvent += ScanHook_BarCodeEvent;
                    scanHook.Start();
                }
                else
                {
                    if (userModel != null)
                    {
                        TextBoxName.Text = userModel.jobnumber;
                    }
                    viewModel.Enable = true;
                    BorderStart.Background = OkColor;
                    PackIconStart.Kind = MaterialDesignThemes.Wpf.PackIconKind.Play;
                    PoptipStart.Content = "开始采集";
                    //server.Stop();
                    scanHook.Stop();                   
                    timer1.Stop();
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("SQL"))
                {
                    HandyControl.Controls.MessageBox.Error("数据库连接异常");
                }
                else
                {
                    HandyControl.Controls.MessageBox.Error(ex.Message);
                }
                FileHelper.WriteLog(ex.ToString());
            }
        }

        private void BorderStart_MouseMove(object sender, MouseEventArgs e)
        {
            this.Cursor = Cursors.Hand;
        }

        private void BorderStart_MouseLeave(object sender, MouseEventArgs e)
        {
            this.Cursor = Cursors.Arrow;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            bool wait = false;
            //lock (listLock)
            //{
            //    foreach (var item in viewModel.Items)
            //    {
            //        if (item.BackColor != WaitColor )
            //        {
            //            wait = true;
            //            break;
            //        }
            //    }
            //}
            if (wait == true)
            {
                MessageBoxResult messageBoxResult = HandyControl.Controls.MessageBox.Ask("还有未上传的数据，是否退出？");
                if (messageBoxResult != MessageBoxResult.OK)
                {
                    e.Cancel = true;
                }
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            ConfigHelper.Write("wkposition", ComboBoxWkPosition.Text);
            ConfigHelper.Write("line", ComboBoxLine.Text);
            ConfigHelper.Write("jiwei", TextBoxJiWei.Text);
            if (userModel != null)
            {
                ConfigHelper.Write("name", userModel.jobnumber);
            }
            System.Environment.Exit(0);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            order = "";
            TextBoxOrder.Text = order;
        }

        public void SetPie()
        {
            int pass = 0;
            int fail = 0;
            lock (listLock)
            {
                foreach (var item in viewModel.Items)
                {
                    if (item.BackColor == NgColor)
                    {
                        fail++;
                    }
                    if (item.BackColor == PassColor || item.BackColor == OkColor)
                    {
                        pass++;
                    }
                }
            }
            if (viewModel.Pass[0] != pass || viewModel.Fail[0] != fail)
            {
                viewModel.Pass[0] = pass;
                viewModel.Fail[0] = fail;
            }
        }
        public void SetList(string serial, string wknum)
        {
            Dispatcher.Invoke(() =>
            {
                TextBoxOrder.Text = order;
                lock (listLock)
                {
                    ViewModel.MainViewModel.Item item = new ViewModel.MainViewModel.Item()
                    {
                        No = viewModel.Items.Count + 1,
                        MoCode = wknum,
                        BarCode = serial,
                        BackColor = WaitColor,
                        Pk_id = null
                    };
                    if (viewModel.Items.Count > 0)
                    {
                        var model = viewModel.Items.Where(it => it.BarCode == serial).FirstOrDefault();
                        if (model == null)
                        {
                            viewModel.Items.Add(item);
                            List.ScrollIntoView(List.Items[item.No - 1]);
                        }
                        else
                        {
                            model.Pk_id = null;
                            model.BackColor = WaitColor;
                            List.ScrollIntoView(List.Items[model.No - 1]);
                        }
                    }
                    else
                    {
                        viewModel.Items.Add(item);
                        List.ScrollIntoView(List.Items[item.No - 1]);
                    }
                }
            });
        }
        private void ScanHook_BarCodeEvent(KeyboardHook.InputCodes barCode)
        {
            try
           {
                string code = barCode.InputStr.Trim().ToUpper();
                //string code = "FV3206787";
                bool isPass = false;
                string wknum = "";
                string errMsg = "";
                if (wkposition == "THT通用测试" || wkposition == "THT加密升级")
                {
                    wknum = code.Substring(0, 10);
                    isPass = mesBLL.CheckWknum(ref order, wknum, ref errMsg);
                    if (isPass == false)
                    {
                        HandyControl.Controls.MessageBox.Show(errMsg);
                        return;
                    }
                    this.SetList(code, wknum);
                    Task.Run(() =>
                    {
                        DateTime scanTime = DateTime.Now;
                        var outTime = DateTime.Now.AddSeconds(300);
                        string path = "D:\\测试记录\\" + wknum + "\\" + code;
                        while (Directory.Exists(path) == false)
                        {
                            if (outTime < DateTime.Now)
                            {
                                return;
                            }
                            Task.Delay(500).Wait();
                        }
                        while (Directory.GetFiles(path).Count() == 0)
                        {
                            if (outTime < DateTime.Now)
                            {
                                return;
                            }
                            Task.Delay(500).Wait();
                        }
                    label1:
                        var files = new DirectoryInfo(path).GetFiles()
                        .Where(it => it.CreationTime > scanTime && (it.FullName.Contains("OK") || it.FullName.Contains("NG")))
                        .ToList();
                        if (files.Count == 0)
                        {
                            if (outTime < DateTime.Now)
                            {
                                return;
                            }
                            Task.Delay(500).Wait();
                            goto label1;
                        }
                        var item1 = this.viewModel.Items.FirstOrDefault(it => it.BarCode == code);
                        foreach (var item in files)
                        {
                            if (item.FullName.Contains("OK"))
                            {
                                Sql2Helper.hkws hkws = new Sql2Helper.hkws()
                                {
                                    MoCode = wknum,
                                    plcode = line,
                                    Jiwei = int.Parse(Jiwei),
                                    Gongwei = userModel.username,
                                    prodBarCode = code
                                };
                                hkws.id_wo = int.Parse(DateTime.Now.ToString("yyyyMMdd"));
                                hkws.createTime = DateTime.Now;
                                Task.Factory.StartNew(() =>
                                {
                                    try
                                    {
                                        Sql8Helper.order_work order_Work = hikVisonDAL.GetPlanMain(hkws.MoCode);
                                        if (order_Work == null)
                                        {
                                            HandyControl.Controls.MessageBox.Error("未获取到" + hkws.MoCode + "的订单信息", this.Title);
                                            return;
                                        }
                                        hkws.ProduceModel = order_Work.material_name;
                                        //2.2
                                        hikVisonDAL.UpTHTGuoZhan(hkws);
                                        if (wkposition == "THT通用测试")
                                        {
                                            //sql 10 边缘数据库
                                            hikVisonDAL.UpTHTGuoZhan2(hkws);
                                        }
                                        //hikVisonDAL.UpPlanDetail(t_Proc_Plan_Main.id, hkws.createTime.ToString("yyyy-MM-dd"));
                                    }
                                    catch (Exception ex)
                                    {
                                        string hkwsJson = JsonConvert.SerializeObject(hkws);
                                        FileHelper.WriteJson(hkwsJson, "过站数据", hkws.prodBarCode + ".txt");
                                        FileHelper.WriteLog(ex.ToString());
                                    }
                                });
                                Dispatcher.Invoke(new Action(() =>
                                {
                                    item1.BackColor = PassColor;
                                    change = true;
                                }));
                                return;
                            }
                            if (item.FullName.Contains("NG"))
                            {
                                Dispatcher.Invoke(new Action(() =>
                                {
                                    item1.BackColor = NgColor;
                                    change = true;
                                }));
                                return;
                            }
                        }
                    });
                }
                if (operation.Contains("手动高清"))
                {
                    wknum = hikVisonDAL.GetWkNum(code);
                    if (string.IsNullOrEmpty(wknum))
                    {
                        HandyControl.Controls.MessageBox.Show( code + "查询工单失败!");
                        return;
                    }
                    isPass = mesBLL.CheckWknum(ref order, wknum, ref errMsg);
                    if (isPass == false)
                    {
                        HandyControl.Controls.MessageBox.Show(errMsg);
                        return;
                    }
                    isPass = hikVisonDAL.CheckHDGuoZhan(isQimi, isZhuangpei, code, line, ref errMsg);
                    if (isPass == false)
                    {
                        HandyControl.Controls.MessageBox.Show(errMsg);
                        return;
                    }
                    this.SetList(code, wknum);
                    Task.Run(() =>
                    {
                        DateTime scanTime = DateTime.Now;
                        var outTime = DateTime.Now.AddSeconds(600);
                        string path = @"d:\HIK\" + DateTime.Today.ToString("yyyyMM") + "\\" + DateTime.Today.ToString("yyyyMMdd");
                        while (Directory.Exists(path) == false)
                        {
                            if (outTime < DateTime.Now)
                            {
                                return;
                            }
                            Task.Delay(500).Wait();
                        }
                        while (Directory.GetFiles(path).Count() == 0)
                        {
                            if (outTime < DateTime.Now)
                            {
                                return;
                            }
                            Task.Delay(500).Wait();
                        }
                    label1:
                        var files = new DirectoryInfo(path).GetFiles()
                        .Where(it => it.CreationTime > scanTime && it.FullName.Contains(code) && it.FullName.Contains(".txt") && it.FullName.Contains("result") )
                        .ToList();
                        if (files.Count == 0)
                        {
                            if (outTime < DateTime.Now)
                            {
                                return;
                            }
                            Task.Delay(500).Wait();
                            goto label1;
                        }
                        var item1 = this.viewModel.Items.FirstOrDefault(it => it.BarCode == code);
                        foreach (var item in files)
                        {
                            if (item.FullName.Contains("result"))
                            {
                                StringBuilder sb = new StringBuilder();
                                using (FileStream fileStream = new FileStream(item.FullName, FileMode.Open))
                                {
                                    StreamReader sr = new StreamReader(fileStream, Encoding.Default);
                                    string line;
                                    while ((line = sr.ReadLine()) != null)
                                    {
                                        sb.AppendLine(line);
                                    }
                                    sr.Close();
                                    fileStream.Close();
                                }
                                isPass = hikVisonDAL.UpHDGuoZhan(code, userModel.username, sb.ToString());
                                if (isPass == false)
                                {
                                    item1.BackColor = NgColor;
                                    errMsg = "过站数据上传失败，请重新测试";
                                    break;
                                }
                                try
                                {
                                    DetectionResult detection = new DetectionResult()
                                    {
                                        Serial = code,
                                        StartTime = scanTime.ToString("G"),
                                        EndTime = item.LastWriteTime.ToString("G"),
                                        Result =ResultStatus.SUCCESS,
                                        CheckSubItems = new List<CheckSubItem>()
                                    };
                                    string[] temp_data = sb.ToString().Split(Environment.NewLine.ToArray(), StringSplitOptions.RemoveEmptyEntries);
                                    for (int i = 0; i < temp_data.Length; i++)
                                    {
                                        string[] result_data = temp_data[i].Split((char)0x09);
                                        int input = 0; 
                                        if (int.TryParse(result_data.FirstOrDefault(), out input))
                                        {
                                            detection.CheckSubItems.Add(new CheckSubItem()
                                            {
                                                ID = (i + 1).ToString(),
                                                Name = result_data.Skip(2).Take(1).FirstOrDefault(),
                                                Description = result_data.Skip(5).Take(1).FirstOrDefault(),
                                                StartTime = detection.StartTime,
                                                EndTime = detection.EndTime,
                                                Result = ResultStatus.SUCCESS,
                                                Items = new List<Item>()
                                                {
                                                    new Item()
                                                    {
                                                        ID= (i + 1).ToString(),
                                                        Type = "KeyInfo",
                                                        Name = result_data.Skip(2).Take(1).FirstOrDefault(),
                                                        Description = result_data.Skip(5).Take(1).FirstOrDefault(),
                                                        Result = ResultStatus.SUCCESS,
                                                    }
                                                }
                                            });
                                        }
                                    }
                                    DateTime time = DateTime.Now;
                                    var pk = $"{lifnr}{code}{time.ToString("yyyyMMddHHMMssfff")}";
                                    hikDataBLL.PostHikDate(detection, item1.MoCode, pk);
                                }
                                catch (Exception ex)
                                {
                                    FileHelper.WriteLog(ex.ToString());
                                }
                                Dispatcher.Invoke(new Action(() =>
                                {
                                    item1.BackColor = PassColor;
                                    change = true;
                                }));
                                return;
                            }
                        }

                    });
                }
            }
            catch (Exception ex)
            {
            }
        }
        //public void TCPInit(int type)
        //{
        //    try
        //    {
        //        commonDetecHelper = new CommonDetecHelper(type, dataHandler);//通用检测协议解析帮助类
        //        server.ClientConnected += new EventHandler<AsyncEventArgs>(server_ClientConnected);
        //        server.ClientDisconnected += new EventHandler<AsyncEventArgs>(server_ClientDisconnected);
        //        server.DataReceived += new EventHandler<AsyncEventArgs>(DataReviced);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //}
        //private void dataHandler(TcpClient client, string data)
        //{
        //    try
        //    {
        //        bool isPass = true;
        //        string errMsg = "";
        //        SocketTransferData transData = JsonConvert.DeserializeObject<SocketTransferData>(data);
        //        string serial = String.Empty;

        //        switch (transData.Name)
        //        {
        //            case "VerifyData"://校验命令
        //                VerifyData verifyData = JsonConvert.DeserializeObject<VerifyData>(transData.Data);
        //                serial = verifyData.Serial;
        //                //dosomething: 做序列号校验（工序），无校验则直接响应成功
        //                string wknum = "";
        //                FileHelper.WriteLog("调用工序校验接口");
        //                if (operation.Contains("THT"))
        //                {
        //                    isPass = OperationBLL.OperationCheck(serial, "测试", ref errMsg, ref wknum);
        //                }
        //                else
        //                {
        //                    isPass = OperationBLL.OperationCheck(serial, operation, ref errMsg, ref wknum,"10.106.26");
        //                }
        //                FileHelper.WriteLog("调用完成");
        //                if (isPass == false)
        //                {
        //                    break;
        //                }
        //                isPass = mesBLL.CheckWknum(ref order, wknum, ref errMsg);
        //                if (isPass == false)
        //                {
        //                    break;
        //                }
        //                SetList(serial, wknum);
        //                break;
        //            case "DetectionResult"://检测结果命令
        //                DetectionResult detectionResult = JsonConvert.DeserializeObject<DetectionResult>(transData.Data);
        //                serial = detectionResult.Serial;
        //                //dosomething:  可以根据detectionResult，调接口将检测结果存后台
        //                string pk = "";
        //                ViewModel.MainViewModel.Item item1 = null;
        //                lock (listLock)
        //                {
        //                    item1 = viewModel.Items.Where(it => it.BarCode == serial).FirstOrDefault();
        //                    DateTime time = DateTime.Now;
        //                    pk = $"{lifnr}{serial}{time.ToString("yyyyMMddHHMMssfff")}";
        //                    if (item1 != null)
        //                    {
        //                        string operation_name = operation.Contains("THT") ? "测试" : operation;

        //                        MesTool.Model.HttpModel.CheckdataDto checkdataPost = new MesTool.Model.HttpModel.CheckdataDto()
        //                        {
        //                            serial_number = serial,
        //                            operation_name = operation_name,
        //                            user_name = userModel.nickName,
        //                            quality = detectionResult.Result.Equals(ResultStatus.SUCCESS) ? "OK" : "NG",
        //                        };
        //                        FileHelper.WriteLog("调用过站记录保存接口");
        //                        isPass = mesBLL.PostCheckdata(checkdataPost, ref errMsg);
        //                        FileHelper.WriteLog("调用完成");
        //                        if (isPass == false)
        //                        {
        //                            item1.BackColor = NgColor;
        //                            errMsg = "过站记录保存失败，请重新测试\r\n" + errMsg;
        //                            break;
        //                        }
        //                        MesTool.Model.HttpModel.BarcodestatusDto barcodestatusPost = new MesTool.Model.HttpModel.BarcodestatusDto
        //                        {
        //                            serial_number = serial,
        //                            operation_name = operation_name,
        //                            quality = detectionResult.Result.Equals(ResultStatus.SUCCESS) ? "OK" : "NG",
        //                        };
        //                        FileHelper.WriteLog("调用更新序列号状态接口");
        //                        isPass = mesBLL.PostBarcodestatus(barcodestatusPost, ref errMsg);
        //                        FileHelper.WriteLog("调用完成");
        //                        if (isPass == false)
        //                        {
        //                            item1.BackColor = NgColor;
        //                            errMsg = "更新序列号状态失败，请重新测试\r\n" + errMsg;
        //                            break;
        //                        }
        //                        #region 
        //                        if (wkposition.Contains("网络"))
        //                        {
        //                            //isPass = hikVisonDAL.UpHDGuoZhan(serial, userModel.nickName);
        //                            //if (isPass == false)
        //                            //{
        //                            //    item1.BackColor = NgColor;
        //                            //    errMsg = "过站数据上传失败，请重新测试";
        //                            //    break;
        //                            //}
        //                        }
        //                        else
        //                        {
        //                            Sql2Helper.hkws hkws = new Sql2Helper.hkws()
        //                            {
        //                                MoCode = item1.MoCode,
        //                                plcode = line,
        //                                Jiwei = int.Parse(Jiwei),
        //                                Gongwei = userModel.nickName,
        //                                prodBarCode = serial
        //                            };
        //                            hkws.id_wo = int.Parse(time.ToString("yyyyMMdd"));
        //                            hkws.createTime = time;
        //                            Task.Factory.StartNew(() =>
        //                            {
        //                                try
        //                                {
        //                                    Sql5Helper.order_work order_Work = hikVisonDAL.GetPlanMain(hkws.MoCode);
        //                                    if (order_Work == null)
        //                                    {
        //                                        HandyControl.Controls.MessageBox.Error("未获取到" + hkws.MoCode + "的订单信息");
        //                                        return;
        //                                    }
        //                                    hkws.ProduceModel = order_Work.material_name;
        //                                    //2.2
        //                                    hikVisonDAL.UpTHTGuoZhan(hkws);
        //                                    if (wkposition == "THT通用测试")
        //                                    {
        //                                        //sql 10 边缘数据库
        //                                        hikVisonDAL.UpTHTGuoZhan2(hkws);
        //                                    }
        //                                    //hikVisonDAL.UpPlanDetail(t_Proc_Plan_Main.id, hkws.createTime.ToString("yyyy-MM-dd"));
        //                                }
        //                                catch (Exception ex)
        //                                {
        //                                    string hkwsJson = JsonConvert.SerializeObject(hkws);
        //                                    FileHelper.WriteJson(hkwsJson, "过站数据", hkws.prodBarCode + ".txt");
        //                                    FileHelper.WriteLog(ex.ToString());
        //                                }
        //                            });
        //                        }
        //                        #endregion
        //                        if (detectionResult.Result.Equals(ResultStatus.SUCCESS))
        //                        {
        //                            item1.BackColor = PassColor;
        //                        }
        //                        else
        //                        {
        //                            item1.BackColor = NgColor;
        //                        }
        //                    }
        //                }
        //                Task.Factory.StartNew(() =>
        //                {
        //                    if (item1 != null)
        //                    {
        //                        hikDataBLL.PostHikDate(detectionResult, item1.MoCode, pk);
        //                        item1.Pk_id = pk;
        //                        change = true;
        //                    }
        //                });
        //                break;
        //        }

        //        byte[] responsedata = commonDetecHelper.BuildSucessResponse(transData.Name, serial);//成功响应
        //        if (isPass == false)
        //        {
        //            responsedata = commonDetecHelper.BuildFaildResponse(transData.Name, serial, errMsg);//失败响应
        //        }
        //        server.Send(client, responsedata);

        //        change = true;
        //    }
        //    catch (Exception ex)
        //    {
        //        HandyControl.Controls.MessageBox.Error(ex.Message);
        //        FileHelper.WriteLog(ex.ToString());
        //    }
        //}

        //public void server_ClientConnected(object sender, AsyncEventArgs e)
        //{
        //    IPEndPoint endpoint = (IPEndPoint)e._state.TcpClient.Client.RemoteEndPoint;
        //}

        //public void server_ClientDisconnected(object sender, AsyncEventArgs e)
        //{
        //    IPEndPoint endpoint = (IPEndPoint)e._state.TcpClient.Client.RemoteEndPoint;
        //}


        //public void DataReviced(object sender, AsyncEventArgs e)
        //{
        //    IPEndPoint endpoint = (IPEndPoint)e._state.TcpClient.Client.RemoteEndPoint;
        //    AsyncTCPServer sevice = sender as AsyncTCPServer;
        //    commonDetecHelper.RecovedSocketData(e._state.TcpClient, e._state.Buffer, 0, e._state.ReciveDataSize);
        //}

        private void ComboBoxLine_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //pline = t_org_trees[ComboBoxLine.SelectedIndex].id;
        }
    }
}
